<template>
  <el-container>
    <el-header>
      <div style="margin-top: 20px;">
        <el-page-header @back="back">
          <template slot="title">返回列表</template>
          <template slot="content">
            <el-button type="success" icon="el-icon-check" v-on:click="save(false)">保存</el-button>
            <el-button type="success" icon="el-icon-finished" v-on:click="save(true)">提交</el-button>
            <el-button type="primary" icon="el-icon-s-flag" v-on:click="showVersion = true">版本</el-button>
          </template>
        </el-page-header>
      </div>
    </el-header>
    <el-main>
      <el-tabs @tab-click="tabClick">
        <el-tab-pane label="基本信息">
          <el-container>
            <el-main>
              <el-row>
                <el-col :span="12">
                  <el-form label-width="100px">
                    <el-form-item label="名称">
                      <el-input v-model="model.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="标题">
                      <el-input v-model="model.content.title" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="图标">
                      <el-button type="text" @click="showIconList = true">
                        <template v-if="model.content.icon">
                          <i :class="model.content.icon"></i>
                        </template>
                        <template v-else>请选择一个图标</template>
                      </el-button>
                    </el-form-item>
                    <el-form-item label="样式名">
                      <el-input v-model="model.content.classes" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="显示标头">
                      <el-switch v-model="model.content.showHeader"></el-switch>
                    </el-form-item>
                    <el-form-item label="显示页脚">
                      <el-switch v-model="model.content.showFooter"></el-switch>
                    </el-form-item>
                    <el-form-item label="规格(列 x 行)">
                      <el-input-number v-model="model.content.colSpan" style="width:80px" step-strictly controls-position="right"
                        :min="1" :max="12" label="列"></el-input-number>x
                      <el-input-number v-model="model.content.rowSpan" style="width:80px" step-strictly controls-position="right"
                        :min="1" :max="6" label="行"></el-input-number>
                    </el-form-item>
                    <el-form-item label="入口地址">
                      <el-input v-model="model.content.enterUri"></el-input>
                    </el-form-item>
                    <el-form-item label="描述(可选)">
                      <el-input v-model="model.content.description" type="textarea" :rows="6"></el-input>
                    </el-form-item>
                  </el-form>
                </el-col>
                <el-col :span="12">
                  <el-form label-width="100px">
                    <el-form-item label="数据源url">
                      <el-input v-model="model.content.dataUri"></el-input>
                    </el-form-item>
                    <el-form-item label="http方法">
                      <el-select v-model="model.content.method" placeholder="请选择http方法">
                        <el-option v-for="method in httpMethods" :key="method" :label="method" :value="method"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="轮询时长">
                      <el-slider v-model="interval" :min="0" :max="600" :step="30"></el-slider>
                      <label class="control-label pull-left">
                        <b style="color:green">{{ interval }}</b>秒，默认值：60秒，为0则不轮询
                      </label>
                    </el-form-item>
                    <el-form-item label="延迟执行">
                      <el-slider v-model="delay" :min="0" :max="120" :step="5"></el-slider>
                      <label class="control-label pull-left">
                        <b style="color:green">{{ delay }}</b>秒，默认值：0秒，为0则不延迟
                      </label>
                    </el-form-item>
                    <el-form-item label="参数设置">
                      <el-tabs style="height: 300px;">
                        <el-tab-pane label="header参数">
                          <div style="height:100%;padding:10px 0;">
                            <el-table height="100%" :data="headers">
                              <el-table-column header-align="left" align="left" label="键" width="100">
                                <template slot-scope="scope">
                                  <el-input v-model="scope.row.key"></el-input>
                                </template>
                              </el-table-column>
                              <el-table-column header-align="left" align="left" label="值" width="100">
                                <template slot-scope="scope">
                                  <el-input v-model="scope.row.val"></el-input>
                                </template>
                              </el-table-column>
                              <el-table-column label="操作" header-align="center" align="center" width="50">
                                <template slot="header">
                                  <el-button type="text" icon="el-icon-circle-plus" @click="headers.push({ key: null, val: null })"></el-button>
                                </template>
                                <template slot-scope="scope">
                                  <el-button type="text" icon="el-icon-remove" @click="headers.remove(scope.row)"></el-button>
                                </template>
                              </el-table-column>
                            </el-table>
                          </div>
                        </el-tab-pane>
                        <el-tab-pane label="url参数">
                          <div style="height:100%;padding:10px 0;">
                            <el-table height="100%" :data="params">
                              <el-table-column header-align="left" align="left" label="键" width="100">
                                <template slot-scope="scope">
                                  <el-input v-model="scope.row.key"></el-input>
                                </template>
                              </el-table-column>
                              <el-table-column header-align="left" align="left" label="值" width="100">
                                <template slot-scope="scope">
                                  <el-input v-model="scope.row.val"></el-input>
                                </template>
                              </el-table-column>
                              <el-table-column label="操作" header-align="center" align="center" width="50">
                                <template slot="header">
                                  <el-button type="text" icon="el-icon-circle-plus"
                                    @click="params.push({ key: null, val: null })"></el-button>
                                </template>
                                <template slot-scope="scope">
                                  <el-button type="text" icon="el-icon-remove" @click="params.remove(scope.row)"></el-button>
                                </template>
                              </el-table-column>
                            </el-table>
                          </div>
                        </el-tab-pane>
                        <el-tab-pane label="post参数">
                          <div style="height:100%;padding:10px 0;">
                            <el-input type="textarea" :rows="2" placeholder="请输入post参数(json格式)" v-model="model.content.data"></el-input>
                          </div>
                        </el-tab-pane>
                      </el-tabs>
                    </el-form-item>
                  </el-form>
                </el-col>
              </el-row>
            </el-main>
          </el-container>
        </el-tab-pane>
        <el-tab-pane label="模板">
          <mf-monacoEditor ref="editor" v-model="model.content.template" language="html" theme="vs-dark"></mf-monacoEditor>
        </el-tab-pane>
        <el-tab-pane label="脚本">
          <mf-monacoEditor ref="scripter" v-model="model.content.script" language="javascript" theme="vs-dark"></mf-monacoEditor>
        </el-tab-pane>
      </el-tabs>
      <el-drawer :title="'[' + model.name + ']所有版本'" :visible.sync="showVersion" @closed="versionClosed" direction="rtl" size="40%" >
        <mf-versioning :repo="repo" :workItem="model" comparable @compare="compareVersion" ></mf-versioning>
      </el-drawer>
      <el-dialog title="选择图标" width="600" :visible.sync="showIconList" :close-on-click-modal="false">
        <mf-icon-list v-model="model.content.icon" @iconSelected="iconSelected"></mf-icon-list>
      </el-dialog>
    </el-main>
  </el-container>
</template>
<script>
import { mapGetters, mapActions } from 'vuex';
const STORE_MODULE = {
  "getters": [
  ],
  "name": "widget",
  "actions": [
    "item",
    "create",
    "update"
  ]
};
export default {
  data() {
    return {
      repo: "portlet",
      newItem: false,
      showVersion: false,
      showIconList: false,
      headers: [],
      params: [],
      model: {
        name: "",
        content: {
          name: "",
          title: "",
          icon: "",
          showHeader: true,
          showFooter: true,
          enterUrl: "",
          colSpan: 4,
          rowSpan: 4,
          classes: "",
          template: "",
          script: "",
          delay: 0,
          interval: 60000,
          dataUrl: "",
          method: "post",
          headers: {},
          params: {},
          data: "",
          description: ""
        },
        submitted:false,
      },
      httpMethods: ["get", "post", "head", "delete", "put"]
    };
  },
  computed: {
    ...mapGetters(STORE_MODULE.getters),
    interval: {
      get() {
        return this.model.content.interval / 1000;
      },
      set(val) {
        this.model.content.interval = val * 1000;
      }
    },
    delay: {
      get() {
        return this.model.content.delay / 1000;
      },
      set(val) {
        this.model.content.delay = val * 1000;
      }
    }
  },
  watch: {
    headers: {
      handler(newVal) {
        let obj = {};
        newVal.forEach(element => {
          obj[element.key] = element.val;
        });
        this.model.content.headers = obj;
      },
      deep: true
    },
    params: {
      handler(newVal) {
        let obj = {};
        newVal.forEach(element => {
          obj[element.key] = element.val;
        });
        this.model.content.params = obj;
      },
      deep: true
    }
  },
  created() {
    this.loadObject();
  },
  methods: {
    ...mapActions(STORE_MODULE.name, STORE_MODULE.actions),
    tabClick(tab, event) {
      this.$nextTick(() => {
        if (this.$refs.editor)
          this.$refs.editor.layout();
        if (this.$refs.scripter)
          this.$refs.scripter.layout();
      });
    },
    back() {
      this.$router.push({ name: "widget" });
    },
    loadObject() {
      let name = this.$route.params.name;
      this.model.name = name;
      this.model.content.name = name;
      this.item(name).then(response => {
        if (response.success){
          if (response.data) {
            this.model = response.data;
            this.model.content.headers = this.model.content.headers || [];
            this.model.content.params = this.model.content.params || [];
          }
          else{
            this.newItem = true;
          }
        }
      });
    },
    save(commit) {
      let task = this.newItem ? this.create : this.update;
      task(this.model).then(response => {
        if (response.success) {
          this.newItem = false;
          this.model = response.data;
          if (commit) {
            prompt("请填写备注", "提交", "", val => {
              this.$service.version
                .commit({ routeData: {repo: this.repo}, data: { name: this.model.name, comment: val } })
                .then(response => {
                  if (response.success) {
                    alert("提交成功", "消息", "success", this.back);
                  }
                });
            });
          } else {
            alert("保存成功", "消息", "success");
          }
        } else {
          if (response.message) alert(response.message, "错误", "error");
        }
      });
    },
    versionClosed() {
      this.showVersion = false;
    },
    compareVersion(arg) {
      arg.callback(this.model.content);
    },
    iconSelected() {
      this.showIconList = false;
    }
  }
};
</script>
